package com.vrv.netmgr.alarm.detail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;
import com.vrv.netmgr.assets.AdvanceSofterwareQueryActivity;
import com.vrv.netmgr.assets.DeviceIPOccupyQryActivity;
import com.vrv.netmgr.assets.DeviceInfoQryActivity;
import com.vrv.netmgr.vo.SerializableAuditInfoQry;
import com.vrv.netmgr.vo.SerializableDeviceIPOccupyQry;
import com.vrv.netmgr.vo.SerializableDeviceInfoQry;
/**
 * @Description 设备审计报警详情
 * @author yzj
 * @date
 * 
 */
@SuppressLint("HandlerLeak")
public class DetailAuditInfoQryActivity extends Activity {
	// 存储数据的数组列表
	private ListViewItemClick listItemClk = new ListViewItemClick();
	private ArrayList<HashMap<String, Object>> listAudit = new ArrayList<HashMap<String,Object>>();
	private ArrayList<HashMap<String, Object>> listAlarm = new ArrayList<HashMap<String,Object>>();
	private ListView listView;
	private ListAdapter adapter = new ListAdapter(); 
	//
	public String TYPE = "type";
	public String EVENT_NAME = "eventName";
	public String TOTAL_COUNT = "totalCount";
	//
	public boolean netDurIsZero = true ;
	private int flag = 0;
	public SerializableAuditInfoQry info;
	//
	private View loadMoreView;
	//总记录数
	public int RECORD_COUNT;
	//当前页号
	public int CUR_INDEX;
	//等待对话框
	private ProgressDialog progressDialog;
	//查询成功
	private static final int QUERY = 3;
	private static final int NET_ERR = 4;
	private static final int QRY_AUDIT = 5;
	private static final int QRY_ALARM = 6;
	// PopWindow检索条件相关
	private ImageButton moreFuncBtn;
	private PopupWindow pwMyPopWindow;
	private ListView lvPopupList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.assets_list_page);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tools_title);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		//
		info = (SerializableAuditInfoQry) getIntent().getSerializableExtra("info");
		init();
		//开始查询数据
		progressDialog = ProgressDialog.show(DetailAuditInfoQryActivity.this, "", "查询中...", true, true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				//Looper.prepare();
				getDataFromServer(0, true);
				//返回数据成功消息
				handler.sendEmptyMessage(QUERY);
				//Looper.loop();
			}
		}).start();
	}
	//处理器
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY:
				findViews();
				break;
			case NET_ERR:
				Toast.makeText(DetailAuditInfoQryActivity.this, "网络连接失败",Toast.LENGTH_LONG).show();
				break;
			case QRY_AUDIT:
				listView.setVisibility(View.VISIBLE);
				adapter.setNetDur(true);
				listItemClk.setNetDur(true);
				adapter.clear();
				initializeAdapter();
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			case QRY_ALARM:
				listView.setVisibility(View.VISIBLE);
				adapter.setNetDur(false);
				listItemClk.setNetDur(false);
				adapter.clear();
				initializeAdapter();
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			}
		}
	};
	//
	private void init(){
		setTitle();
	}
	//初始化listview的适配器
	public void initializeAdapter() {
		if(0 == flag){
			for (int i = 0; i < listAudit.size(); i++) {
				adapter.addItem(listAudit.get(i));
			}
		}else if(1 == flag){
			for (int i = 0; i < listAlarm.size(); i++) {
				adapter.addItem(listAlarm.get(i));
			}
		}
		
	}
	//添加监听
	private class ListViewItemClick implements AdapterView.OnItemClickListener {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			HashMap<String, Object> hashMap = adapter.getData(arg2);
			
		}
	}
	//查询所有数据
	public void getDataFromServer(int pageNum, boolean netDurIsZero) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(GlobalConstants.PAGE_NUM, pageNum + "");
		map.put(GlobalConstants.ERR_TYPE, "0");
		map.put(GlobalConstants.ERR_MSG, GlobalConstants.OPEN_IO_NET);
		map.put(GlobalConstants.NET_DURATION, netDurIsZero + "");
		boolean retVal = qrynetDurIsZero(map, netDurIsZero);
		if (!retVal)
			handler.sendEmptyMessage(NET_ERR);
	}

	public boolean qrynetDurIsZero(Map<String, String> map, boolean netDurIsZero) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext())
				.getUrlPrefix();
		String urlAddr = urlPrefix + "/warningInfo/statistics/warningInfoByDevice.do?deviceId=" + info.getDEV_ID()+ "&classId=1&ipAddress=" 
				+ info.getIP_ADDRESS();
		String response = httpClientToServer.doPost(urlAddr, map);
		Log.i("respones++++",response);
		if (HttpClientToServer.DO_POST_ERR.equals(response)
				|| HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");

			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");

			RECORD_COUNT = count;
//			if (count < 1)
//				return retVal;
//			JSONArray jArr = jsonObj.getJSONArray("records");
//			int jArrLen = jArr.length();
//
//			if (jArrLen > 0) {
//				CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));
//
//			}
			JSONArray jArr = jsonObj.getJSONArray("record");
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				HashMap<String, Object> myMap = new HashMap<String, Object>();
				if("0".equals(jObj.getString("type"))){
					myMap.put(EVENT_NAME, jObj.getString("eventName"));
					myMap.put(TOTAL_COUNT, jObj.getString("totalCount"));
					listAudit.add(myMap);
				}else if("1".equals(jObj.getString("type"))){
					myMap.put(EVENT_NAME, jObj.getString("eventName"));
					myMap.put(TOTAL_COUNT, jObj.getString("totalCount"));
					Log.i("myMap=====",myMap.toString());
					listAlarm.add(myMap);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	public void setTitle() {
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText("设备审计报警");

		/**
		 * 返回按钮
		 */
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
	}

	public void findViews() {
		iniPopupWindow();
		// 更多操作按钮
		moreFuncBtn = (ImageButton) findViewById(R.id.moreFunctionBtn);
		moreFuncBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pwMyPopWindow.isShowing()) {
					pwMyPopWindow.dismiss();// 关闭
				} else {
					pwMyPopWindow.showAsDropDown(moreFuncBtn);// 显示
				}
			}
		});
		listView = (ListView) findViewById(R.id.assets_lv_id);
		if (RECORD_COUNT > 0) {
			listView.setVisibility(View.VISIBLE);
			if (RECORD_COUNT > ListViewUtil.PAGESIZE)
			adapter.setNetDur(true);
			initializeAdapter();
			listView.setAdapter(adapter);
			listItemClk.setNetDur(true);
			listView.setOnItemClickListener(listItemClk);
		}
	}

	private void iniPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.title_func_popupwindow, null);
		lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
		pwMyPopWindow = new PopupWindow(layout);
		pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
        		DetailAuditInfoQryActivity.this, R.layout.list_item_popupwindow,
				R.id.tv_list_item, getResources().getStringArray(
						R.array.infoType));
		lvPopupList.setAdapter(arrayAdapter);
		lvPopupList.setOnItemClickListener(new ClickPopupItemListener(arrayAdapter));
		// 控制popupwindow的宽度和高度自适应
		lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
				View.MeasureSpec.UNSPECIFIED);
		pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
		// pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight()) * 3);
		pwMyPopWindow.setHeight(LayoutParams.WRAP_CONTENT);
		// 控制popupwindow点击屏幕其他地方消失
		pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
				R.drawable.bg_popupwindow));
		// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
		pwMyPopWindow.setOutsideTouchable(true);
    }
	private class ClickPopupItemListener implements AdapterView.OnItemClickListener{
		ArrayAdapter<String> arrayAdapter;
		ClickPopupItemListener(ArrayAdapter<String> arrayAdapter){
			this.arrayAdapter = arrayAdapter;
		}
		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			pwMyPopWindow.dismiss();
			if (loadMoreView != null)
				listView.removeFooterView(loadMoreView);
			if (position == 0) {
				progressDialog = ProgressDialog.show(
						DetailAuditInfoQryActivity.this, "", "查询中...", true, true);
				new Thread(new Runnable() {
					@Override
					public void run() {
//						getDataFromServer(0, true);
						flag = 0;
						handler.sendEmptyMessage(QRY_AUDIT);
					}
				}).start();
			} else if (arrayAdapter.getCount() - 3 == position) {
				Intent intent = new Intent(DetailAuditInfoQryActivity.this,
						AdvanceSofterwareQueryActivity.class);
				startActivity(intent);
			} else {
				progressDialog = ProgressDialog.show(
						DetailAuditInfoQryActivity.this, "", "查询中...", true, true);
				new Thread(new Runnable() {
					@Override
					public void run() {
//						getDataFromServer(0, false);
						flag = 1;
						handler.sendEmptyMessage(QRY_ALARM);
					}
				}).start();
			}
			Toast.makeText(DetailAuditInfoQryActivity.this,
					"" + arrayAdapter.getItem(position).toString(),
					Toast.LENGTH_LONG).show();
		}
	}

	private class ListAdapter extends ListViewAdapter {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final HashMap<String, Object> hashMap = getData(position);
			if (view == null)
				view = LayoutInflater.from(DetailAuditInfoQryActivity.this).inflate(
						R.layout.detail_auditinfoqry, null);

			TextView event = (TextView) view.findViewById(R.id.auditinfo_event);
			TextView count = (TextView) view.findViewById(R.id.auditinfo_count);
			event.setText(hashMap.get(EVENT_NAME).toString());
			Log.i("eventName",hashMap.get(EVENT_NAME).toString());
			count.setText(hashMap.get(TOTAL_COUNT).toString());
			return view;
		}
	}
	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
